var autodb = require('../../db/auto.db');
var config = require('../../config')
var async = require('async');
var logger = require('../../logger')
var emit = require('../../emit')

function removetag(isMusic, fileid, lowtag, cb) {
    async.waterfall([
        (callback) => {
            autodb.getfileinfo(isMusic, fileid, (err, info) => {
                callback(err, info);
            });
        },

        //移除maintag.childtag.grandsontag.tags里面的file
        (info, callback) => {
            let tables = info.maintag + '.' + info.childtag + '.' + lowtag + config.files;
            autodb.client(isMusic).srem(tables, fileid, (err) => {
                callback(err);
            })
        },

        //移除fileid.tags里面的fileid
        (callback) => {
            autodb.client(isMusic).srem(fileid + config.tags, lowtag, (err) => {
                callback(err);
            })
        },
    ], (err) => {
        cb(err);
    })
}

function onsocket(socket, data) {
    if (data == undefined || data.tag == undefined) {
        return;
    }
    var lowtag = data.tag.toLowerCase();
    async.forEach(data.ids, (fileid, cb) => {
        removetag(data.isMusic, fileid, lowtag, (err) => {
            cb(err);
        })
    }, (err) => {
        if (config.debug) {
            logger.log(err);
        } else {
            var protocol = data.isMusic ? 'removetag-music' : 'removetag-sound';
            var result = err ? false : true;
            emit.send(socket, protocol, result);
        }
    })
}

module.exports = {
    onsocket
}